import classNames from 'classnames';
import CSSMotion from 'rc-motion';
import React from 'react';
import TabContext from '../TabContext';
import { TabPanelListProps } from '../interface';
import TabPane from './TabPane';

const TabPanelList: React.FC<TabPanelListProps> = (props) => {
  const { prefixCls, tabs } = React.useContext(TabContext);
  const { id, activeKey, animated, destroyInactiveTabPane, tabPosition } =
    props;
  const tabPaneAnimated = animated?.tabPane;
  const tabPanePrefixCls = `${prefixCls}-tabpane`;

  return (
    <div className={classNames(`${prefixCls}-content-holder`)}>
      <div
        className={classNames(
          `${prefixCls}-content`,
          `${prefixCls}-content-${tabPosition}`,
          {
            [`${prefixCls}-content-animated`]: tabPaneAnimated,
          },
        )}
      >
        {tabs.map(
          ({
            key,
            forceRender,
            paneStyle,
            paneClassName,
            destroyInactiveTabPane: itemDestroyInactiveTabPane,
            children,
          }) => {
            const active = key === activeKey;

            return (
              <CSSMotion
                key={key}
                visible={active}
                forceRender={forceRender}
                removeOnLeave={
                  !!(destroyInactiveTabPane || itemDestroyInactiveTabPane)
                }
                leavedClassName={`${tabPanePrefixCls}-hidden`}
              >
                {({ style: motionStyle, className: motionClassName }, ref) => {
                  return (
                    <TabPane
                      prefixCls={tabPanePrefixCls}
                      id={id}
                      tabKey={key}
                      active={active}
                      style={{
                        //一定要把cssMotion的style/class注入
                        ...paneStyle,
                        ...motionStyle,
                      }}
                      className={classNames(paneClassName, motionClassName)}
                      children={children}
                      ref={ref}
                    />
                  );
                }}
              </CSSMotion>
            );
          },
        )}
      </div>
    </div>
  );
};

export default TabPanelList;
